﻿using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace Zhaoxi.AuthenticationCenter.Utility
{
    public class SingleEmailRequirement : AuthorizationHandler<SingleEmailRequirement>, IAuthorizationRequirement
    {
        public SingleEmailRequirement(string requiredName)
        {
            if (requiredName == null)
            {
                throw new ArgumentNullException(nameof(requiredName));
            }

            RequiredName = requiredName ?? "@qq.com";
        }
        /// <summary>
        /// 邮件域名，默认@qq.com
        /// </summary>
        public string RequiredName { get; }

        /// <summary>
        /// 校验规则
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SingleEmailRequirement requirement)
        {
            Console.WriteLine("This is SingleEmailRequirement HandleRequirementAsync*********");
            if (context.User != null && context.User.HasClaim(c => c.Type == ClaimTypes.Email))
            {
                //去查询数据库
                var emailCliamList = context.User.FindAll(c => c.Type == ClaimTypes.Email);//支持多Scheme
                if (emailCliamList.Any(c => c.Value.EndsWith(RequiredName, StringComparison.OrdinalIgnoreCase)))//数据库校验--Redis校验
                {
                    context.Succeed(requirement);
                }
                else
                {
                    //context.Fail();
                }
            }
            return Task.CompletedTask;
        }

        public override string ToString()
        {
            return $"{nameof(SingleEmailRequirement)}:Requires a user email end with {RequiredName}";
        }
    }
}
